package com.ruoyi.ai.controller;

import com.ruoyi.ai.dto.ChatRequestDTO;
import com.ruoyi.ai.service.ChatService;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import javax.validation.Valid;

/**
 * @author coach tam
 * @email 327395128@qq.com
 * @values 坚持灵活 灵活坚持
 * @since 2025/3/19
 */
@RestController
public class ChatController {

    private final OpenAiChatModel chatModel;

    @Autowired
    public ChatController(OpenAiChatModel chatModel) {
        this.chatModel = chatModel;
    }


    @Autowired
    private ChatService chatService;

    @GetMapping("/chat/stream")
    public Flux<ServerSentEvent<String>> chat(
            @Valid ChatRequestDTO chatRequestDTO
    ) {
        return chatService.chatWithTools(chatRequestDTO).map(res -> {
            String content = res.getResults().get(0).getOutput().getText();
            return ServerSentEvent.<String>builder()
                    .event("chat")  // 设置事件名称为chat
                    .data(content)  // 将数据转换为JSON字符串
                    .build();
        });
    }
}
